﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Oliving.Edge.AuthHelper;
using Oliving.Edge.AuthHelper.OverWrite;
using Oliving.Edge.Common.Helper;
using Oliving.Edge.Common.LogHelper;
using Oliving.Edge.Extensions.XcxExtentsions;
using Oliving.Edge.IServices;
using Oliving.Edge.Model;
using Oliving.Edge.Model.Dto.Xcx;
using Oliving.Edge.Model.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Oliving.Edge.Controllers.Xcx
{
    [Authorize(Permissions.Name)]
    [ApiController]
    public class XUserInfo : OlivingControll
    {
        #region 构造函数注入
        readonly ISysUserInfoServices _sysUserInfoServices;
        readonly PermissionRequirement _requirement;
        private readonly IRoleModulePermissionServices _roleModulePermissionServices;
        /// <summary>
        /// 构造函数注入
        /// </summary>
        /// <param name="sysUserInfoServices">用户基础信息</param>
        public XUserInfo(ISysUserInfoServices sysUserInfoServices, PermissionRequirement requirement, IHttpContextAccessor accessor, IRoleModulePermissionServices roleModulePermissionServices): base(accessor, requirement)
        {
            _sysUserInfoServices = sysUserInfoServices;
            _requirement = requirement;
            _roleModulePermissionServices = roleModulePermissionServices;
        }

        #endregion

        #region  小程序登陆授权  白克平  2020-09-14
        /// <summary>
        /// 小程序登陆授权   
        /// </summary>
        /// <author>白克平</author>
        /// <datetime>2020-9-14</datetime>
        /// <param name="code">微信code</param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/xcx/xcode")]
        [AllowAnonymous]
        public async Task<MessageModel<wxCode>> xcode(string code)
        {
            var data = new MessageModel<wxCode>();
            if (string.IsNullOrEmpty(code))
            {
                data.msg = "code不能为空";
                data.response = null;
                data.success = false;
            }
            WxLogin login = new WxLogin();
            wxCode wxcode = await login.XloginByCode(code);
            //LogLock.OutSql2Log("AOPLog", new string[] { JsonConvert.SerializeObject(wxcode) });
            if (wxcode.errcode == -1)
            {
                data.msg = "系统繁忙，此时请开发者稍候再试";
                data.response = null;
                data.success = false;
            }
            else if (wxcode.errcode == 40029)
            {
                data.msg = "code 无效";
                data.response = null;
                data.success = false;
            }
            else if (wxcode.errcode == 45011)
            {
                data.msg = "刷新太快，请稍后重试";
                data.response = null;
                data.success = false;
            }
            else if (wxcode.errcode == 0)
            {
                data.msg = "请求成功";
                data.response = wxcode;
                data.success = false;
            }
            else
            {
                data.msg = "系统错误，请稍后重试";
                data.response = null;
                data.success = false;
            }
            return data;
        }
        #endregion

        #region 小程序增加用户信息并返回基础信息    白克平 2020-9-14
        /// <summary>
        /// 小程序增加用户信息并返回token 验证
        /// </summary>
        /// <author>白克平</author>
        /// <datetime>2020-9-14</datetime>
        /// <param name="phone">手机号</param>
        /// <param name="wechat">微信用户唯一标示</param>
        /// <returns>用户权限和基础信息</returns>
        [HttpPost]
        [Route("api/xcx/xlogin")]
        public async Task<MessageModel<sysUserInfo>> xlogin(string phone, string wechat, string token)
        {
            var data = new MessageModel<sysUserInfo>();
            if (string.IsNullOrEmpty(phone))
            {
                //手机号不能为空
                data.msg = "手机号不能为空";
                data.success = false;
                return data;
            }
            if (string.IsNullOrEmpty(wechat))
            {
                //用户微信唯一标示不能为空
                data.msg = "用户微信标示不能为空";
                data.success = false;
                return data;
            }
            if (string.IsNullOrEmpty(token))
            {
                //用户微信唯一标示不能为空
                data.msg = "token不能为空";
                data.success = false;
                return data;
            }
            var tokenModel = JwtHelper.SerializeJwt(token);
            if (tokenModel != null && tokenModel.Uid > 0)
            {
                var userinfo = await _sysUserInfoServices.QueryById(tokenModel.Uid);
                if (userinfo != null)
                {
                    data.response = userinfo;
                    data.success = true;
                    data.msg = "成功";
                }
            }
            return data;
        }
        #endregion

        #region 小程序登陆获取token 白克平 2020-9-14   根据手机号登陆
        /// <summary>
        /// 小程序登陆获取token
        /// </summary>
        /// <author>白克平</author>
        /// <datetime>2020-9-14</datetime>
        /// <param name="phone">手机号</param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/xcx/token")]
        public async Task<MessageModel<object>> GetJwtStr(string phone)
        {
            string jwtStr = string.Empty;
            bool suc = false;
            //这里就是用户登陆以后，通过数据库去调取数据，分配权限的操作
            var user = await _sysUserInfoServices.XGetUserRoleNameStr(phone);
            if (user != null)
            {
                //处理角色id
                string roles = string.Join(',', user.Select(r => r.roles).ToArray());
               
                TokenModelJwt tokenModel = new TokenModelJwt { Uid = user.FirstOrDefault().userID, Role = roles };
                jwtStr = JwtHelper.IssueJwt(tokenModel);
                suc = true;
            }
            else
            {
                jwtStr = "登陆失败，请稍后重试";
            }
            return new MessageModel<object>()
            {
                success = suc,
                response = jwtStr,
                msg = "认证失败"
            };
        }
        #endregion

    }
}
